﻿using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace ChivalryUnityEditor
{
    /// <summary>
    /// @Author:Teddy
    /// </summary>
    [CustomPropertyDrawer(typeof(EnumLabelAttribute))]
    public class EnumLabelDrawer : PropertyDrawer
    {
        private GUIContent[] m_enumDisplayNames;
        private int[] m_enumValues;

        private bool m_initialized;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {

            if (property.propertyType != SerializedPropertyType.Enum)
            {
                EditorGUI.LabelField(position, label.text, "EnumLabel 仅支持枚举类型");
                return;
            }
            Initialize();
            EnumLabelAttribute enumLabel = attribute as EnumLabelAttribute;
            EditorGUI.IntPopup(position, property, m_enumDisplayNames, m_enumValues, new GUIContent(enumLabel.Label));
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            if (m_initialized)
                return;

            m_initialized = true;
            FieldInfo[] fields = fieldInfo.FieldType.GetFields(BindingFlags.Static | BindingFlags.Public);
            m_enumDisplayNames = new GUIContent[fields.Length];
            m_enumValues = new int[fields.Length];

            for (int i = 0; i < fields.Length; i++)
            {
                object[] attrs = fields[i].GetCustomAttributes(typeof(EnumLabelAttribute), false);
                GUIContent displayName;
                if (attrs.Length == 0)
                {
                    displayName = new GUIContent(fields[i].Name);
                }
                else
                {
                    EnumLabelAttribute attr = attrs[0] as EnumLabelAttribute;
                    displayName = new GUIContent(attr.Label);
                }
                m_enumDisplayNames[i] = displayName;
                m_enumValues[i] = (int)fields[i].GetValue(null);
            }
        }
    }

    public class EnumLabelAttribute : PropertyAttribute
    {
        public string Label { get; internal set; }

        public EnumLabelAttribute(string label)
        {
            Label = label;
        }
    }
}